﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UWP.Douban.Models;
using UWP.Douban.Utils;

namespace UWP.Douban.Repositories
{
    public class ConfigRepository : Repository
    {
        private static String TABLE_NAME = "Config";
        private static String SQL_CREATE_TABLE = $"CREATE TABLE IF NOT EXISTS {TABLE_NAME} (Key TEXT,Value TEXT,PRIMARY KEY(Key)) ;";
        private static string SQL_INSERT_REPLACE_VALUE = $"Insert or Replace INTO {TABLE_NAME}(Key,Value) Values(?,?)";
        private static string SQL_QUERY_VALUE = $"SELECT Value FROM {TABLE_NAME} where Key = ?";
        private static string AuthenticateKey = "Token";


        public ConfigRepository()
        {
            Execute(SQL_CREATE_TABLE);
        }

        /// <summary>
        /// 获取Token信息
        /// </summary>
        /// <returns>Token</returns>
        public Authenticate GetAuthenticate()
        {
            return JsonUtil.Deserialize<Authenticate>(Query<string>(SQL_QUERY_VALUE, null, AuthenticateKey));
        }

        /// <summary>
        /// 保存Token信息
        /// </summary>
        /// <param name="authenticate">待保存的Token信息</param>
        public void SetAuthenticate(Authenticate authenticate)
        {
            var json = JsonUtil.Serializer(authenticate);

            Execute(SQL_INSERT_REPLACE_VALUE, AuthenticateKey, json);
        }
    }
}
